'use strict';

/* Services
 *
  * 数据初始化
  * 临时数据存储
  *
  * */

angular.module('myApp.MessageStore', ['myApp.MessageModel']).
	factory('MessageStore', ['$filter','Message',function ($filter,Message) {
		var messages = [];
		var userMsg = {};//{username:['msgid','msgid'],gid:['msgid','msgid','msgid']}
		
		function saveUserMsg(uid){
			if(!userMsg[uid])
				userMsg[uid] = [];
			return function(message){
				userMsg[uid].push(message);
			};
		}

        var sendSave = function(message){
            messages.push(message);
            saveUserMsg(message.to)(message.id);
        };

        var receiveSave = function (message) {
            messages.push(message);
            if (message.msgType) {//聊天消息
                saveUserMsg(message.group ? message.to : message.from)(message.id);
            } else if (message.commType) {//命令消息
                saveUserMsg(message.groupId)(message.id);
            }
        }

        var saveMessage = function(message){
            if(message.send){
                sendSave(message);
            }else{
                receiveSave(message)
            }
        }

        var getAllMessage = function(){
            return messages;
        }
        var saveAllMessage = function(messages){
        	this.messages = messages;
        }

        var getMessages = function(contactIdentifier){
            var messageArr = [];
            var msgIds = userMsg[contactIdentifier];
            if(msgIds){
                for(var i=0;i<messages.length;i++){
                    if(msgIds.contains(messages[i].id))
                        messageArr.push(messages[i]);
                };
            };
            //	messageArr = $filter('filter')(messages, {id: msgIds});
            return messageArr;
        }

		return {
            saveMessage : saveMessage,
            saveAllMessage : saveAllMessage,
			sendSave : sendSave,
            receiveSave : receiveSave,
			getAllMessage : getAllMessage,
			getMessages : getMessages
		};
	}]);

angular.module('myApp.DataStore', []).
	factory('DataStore', ['$http','$q', function ($http, $q) {
		var user = null;//当前用户
		var contacts = [];//联系人
		var contactMap = {};
		var groups = [];//群组
		var groupMap = {};
        var deptGroupIdentifiers = [];
        var organizations = [];//组织
        var groupContacts = {};//群组人员  key :groupIdentifier  value: contactIdentifiers

        function sort(array){
            array.sort();//可以进行排序后再返回
        };

        function initDataPromise(){
            var deferred = $q.defer();
            $q.all([queryAllContactPromise(), queryUserGroupsPromise()]).then(function(results){
                deferred.resolve(results[0]);
                tokenListener();//监听token
            },function(errorMsg){
                deferred.reject(errorMsg);
            });
            return deferred.promise;
        }

        var queryAllContactPromise = function(){
            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: 'main.do'
            }).success(function (data){
                if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                    util.tokenExpire();
                    return;
                }
                if(data.error){
                    deferred.reject(data.error);
                    return deferred.promise;
                }
                window.pcWeb = {};
                window.pcWeb.lastRefreshTime = data.lastRefreshTime;
                window.pcWeb.apiAddress = data.apiAddress;
                window.pcWeb.user = data.user;
                window.feedbackAddress = data.feedbackAddress;
                
                var apiAddress = data.apiAddress;
                var obj=null;
                var user = null;
                //变量初始化
                contacts = [];
                contactMap = [];
                for(var i=0;i<data.result.contacts.length;i++){
                    obj = data.result.contacts[i];
                    if(obj.status == 0){
                        continue;
                    }
                    obj.identifier = obj.username;
                    if(obj.department) obj.deptIds = [obj.department];
                    saveContact(obj);
                    if (obj.username == data.user.username) {
                        user = obj;
                        saveUser(obj);
                    }
                }
                //变量初始化
                organizations = [];
                deptGroupIdentifiers = [];
                for(var i=0;i<data.result.organizations.length;i++){
                    obj = data.result.organizations[i];
                    if(obj.status == 0){
                        continue;
                    }
                    saveOrganization(obj);
                    if(obj.groupUid){
                        deptGroupIdentifiers.push(obj.groupUid);
                    }
                }
                deferred.resolve(data.user);
            }).error(function(){
                deferred.reject('请求服务器失败，请稍后再试！');
            });
            return deferred.promise;
        }

        var queryUserGroupsPromise = function(){
            var deferred = $q.defer();
            //查询人员所在群组
            $http({
                method: 'POST',
                url: 'group/userGroups.do'
            }).success(function (data){
                if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                    util.tokenExpire();
                    return;
                }
                if(data.error){
                    deferred.reject(data.error);
                    return deferred.promise;
                }
                groups = [];
                groupMap = {};
                var userGroups = data.userGroups;
                for(var i=0; i<userGroups.length;i++){
                    var group = userGroups[i];
                    group.identifier = group.uid;
                    group.isGroup = true;
                    saveGroup(group);
                }
                deferred.resolve('success');
            }).error(function(){
                deferred.reject('请求服务器失败，请稍后再试！')
            });
            return deferred.promise;
        }

        var tokenInterval = null;
        var tokenListener = function(){
            var tempTime = 0;
            if(tokenInterval != null) clearInterval(tokenInterval);
            tokenInterval = setInterval(function () {
                tempTime += 1000;
                var expires_in = parseInt(window.pcWeb.user.expires_in) * 1000;
                if (expires_in - tempTime < 2000) {//token失效前两秒开始刷新
                    tempTime = 0;
                    refreshToken();
                }
            }, 1000);
        }

        var refreshToken = function(){
            $http({
                method: 'GET',
                url: 'refreshToken.do'
            }).success(function (data) {
                if (data.error) {
                    //console.log(data.error);
                }
                window.pcWeb.user.access_token = data.result.access_token;
                window.pcWeb.user.expires_in = data.result.expires_in;
            }).error(function(){
                //console.log('请求服务器失败，请稍后再试！');
            });
        }

        var saveUser = function(contact){
            user = contact;
        }

        var getUser = function(){
            return user;
        }

        var saveContact = function(contact){
            if(contactMap[contact.identifier] == null){
                contactMap[contact.identifier] = contact;
                contacts.push(contact);
            }else{
                contactMap[contact.identifier] = contact;
                for(var i=0; i<contacts.length; i++){
                    if(contacts[i].identifier == contact.identifier){
                        var tempAvatar = contacts[i].avatar;
                        var tempDeptIds = contacts[i].deptIds;
                        contacts[i] = contact;
                        contacts[i].avatar = tempAvatar;
                        if(contact.deptIds != null && !tempDeptIds.contains(contact.deptIds[0])){
                            tempDeptIds.push(contact.deptIds[0]);
                            contacts[i].deptIds = tempDeptIds;
                        }
                        return;
                    }
                }
            }
        };

        var getContact = function(identifier){
            return contactMap[identifier];
        };

        var getContactMap = function(){
            return contactMap;
        }

        var getContactsByUsernames = function(usernames){
            var contacts = new Array();
            if(usernames!=null){
                for(var i=0; i<usernames.length; i++){
                    contacts.push(contactMap[usernames[i]]);
                }
            }
            return contacts;
        };

        var deleteContact = function(identifier){
            angular.forEach(contacts, function(contact){
                if(contact.identifier == identifier) contacts.remove(contact); return;
            });
            contactMap[identifier] = null;
        }

        var getContacts = function(){
            return contacts;
        };

        var saveOrganization = function(organization){
            organizations.push(organization);
        }

        var getOrganizations = function(){
            return organizations;
        }

        var saveGroup = function(group){
            if(group == null || group.identifier == null){
                return;
            }
            if(groupMap[group.identifier] == null){
                groupMap[group.identifier] = group;
                groups.push(group);
            }else{
                groupMap[group.identifier] = group;
                for(var i=0; i<groups.length; i++){
                    if(groups[i].identifier == group.identifier){
                        groups[i] = group;//update group
                        return;
                    }
                }
            }
        }

        var getGroups = function(){
            return groups;
        }

        var getGroupMap = function(){
            return groupMap;
        }

        var saveGroupContacts = function(groupIdentifier, contactIdentifiers){
            groupContacts[groupIdentifier] = contactIdentifiers;
        }

        var saveGroupContact = function(groupIdentifier, contactIdentifier){
            if(groupContacts[groupIdentifier] == null) return;
            groupContacts[groupIdentifier].push(contactIdentifier);
        }

        var deleteGroupContact = function(groupIdentifier, contactIdentifier){
            if(groupContacts[groupIdentifier] == null) return;
            groupContacts[groupIdentifier].remove(contactIdentifier);
        }

        var getGroupContacts = function(){
            return groupContacts;
        }

        var getDeptGroupIdentifiers = function(){
            return deptGroupIdentifiers;
        }

        return {
            initPromise : initDataPromise,
			saveUser : saveUser,
			getUser : getUser,
			saveContact: saveContact,
			getContact : getContact,
            getContactMap : getContactMap,
            getContactsByUsernames : getContactsByUsernames,
            getContacts : getContacts,
            deleteContact : deleteContact,
			saveOrganization : saveOrganization,
			getOrganizations : getOrganizations,
			saveGroup : saveGroup,
            getGroups : getGroups,
            getGroupMap : getGroupMap,
            saveGroupContacts : saveGroupContacts,
            saveGroupContact : saveGroupContact,
            deleteGroupContact : deleteGroupContact,
            getGroupContacts : getGroupContacts,
            getDeptGroupIdentifiers : getDeptGroupIdentifiers
		};
	}]);


